﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using GameLibrary;
using Rescue_of_the_Dwarvenzombies.Scene;
using Rescue_of_the_Dwarvenzombies.SceneObjects.GameObjects.Characters.Enemies;

namespace Rescue_of_the_Dwarvenzombies.SceneObjects.SceneObjectsHandlers
{
    public class EnemyHandler : IEnemyObserver
    {
        private List<ISceneObject> currentEnemies = new List<ISceneObject>();
        private Game _game;
        private ItemHandler _itemHandler;
        private int totScore;

        /// <summary>
        /// Initializes a new instance of the EnemyHandler class.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <param name="itemHandler">The item handler.</param>
        public EnemyHandler(Game game, ItemHandler itemHandler)
        {
            _game = game;
            totScore = 0;
            _itemHandler = itemHandler;
        }

        /// <summary>
        /// Creates a wave of enemies at said spawn positions and of said enemy types
        /// </summary>
        /// <param name="nrOfZombies"></param>
        /// <param name="nrOfElvanWarriors"></param>
        /// <param name="spawnPositions"></param>
        /// <returns></returns>
        public List<ISceneObject> MakeNewWave(int nrOfZombies, int nrOfElvanWarriors, Vector2[] spawnPositions)
        {
            for (int i = 0; i < nrOfZombies; i++)
            {
                currentEnemies.Add(new Zombie(this, _itemHandler, spawnPositions[i]));
            }

            for (int j = 0; j < nrOfElvanWarriors; j++)
            {
                currentEnemies.Add(new ElvanWarrior(this, _itemHandler, spawnPositions[j]));
            }

            return currentEnemies;
        }

        /// <summary>
        /// Handle the consequences of an enemy dying, if all enemies are dead
        /// a new random wave will appear(just for fun)
        /// </summary>
        /// <param name="enemy">The enemy.</param>
        public void IsDead(Enemy enemy)
        {
            ((ISoundManager)_game.Services.GetService(typeof(ISoundManager))).Play(enemy, Constant.Action.Die);
            
            //Get score from fallen enemy
            totScore += enemy.Score;
            
            currentEnemies.Remove(enemy);

            //for fun
            if (currentEnemies.Count == 0)
            {
                Vector2[] spawnPositions = ((ISceneManager)_game.Services.GetService(typeof(ISceneManager))).GetSpawnPositions();
                MakeNewWave(((ISceneManager)_game.Services.GetService(typeof(ISceneManager))).GetNumberOfEnemies(), 0, spawnPositions);
            }
        }

        /// <summary>
        /// Gets the current enemies.
        /// </summary>
        /// <returns></returns>
        public List<ISceneObject> GetCurrentEnemies()
        {
            return currentEnemies;
        }
    }
}